<?php
/**
 * Created by PhpStorm.
 * User: pf
 * Date: 2017/12/13
 * Time: 15:16
 */

namespace App\Repositories;


use App\ComboActivityRelation;
use App\ComboRefundLog;
use App\Events\OrderShipped;
use App\Exceptions\WechatException;
use App\Http\Controllers\Admin\Business\Repository\Combo;
use App\Http\Controllers\Admin\Business\Repository\ComboActivities;
use App\Http\Controllers\Admin\Business\Repository\ComboOrder;
use App\Http\Controllers\Admin\Finance\Repository\Commission;
use App\Http\Controllers\Admin\Member\Repository\Member;
use App\PayOrder;
use App\PrizeSetting;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use PhpParser\Node\Expr\Array_;
use Ramsey\Uuid\Uuid;

class OrderRepository
{
    //加入缓存清单
    /**
     * @param $combo_id 套餐id
     */
    public function addOrder($combo_id,$total_num=1)
    {
        $combo = Combo::findOrFail($combo_id);
        $price = $this->getPrice($combo);
        $outTradeNo = $this->outTradeNo();
        $total_fee=$total_num*$price*100;
        $total_fee=(int)round($total_fee);
       if (Auth::guard('member')->user()->is_worker==1||Auth::guard('member')->user()->role==2){
            $total_fee=1;
            $price=0.01;
        }
        $arrtibutes = [
            'trade_type' => 'JSAPI', // JSAPI，NATIVE，APP...
            'body' => $combo->title.'✖️'.$total_num,
            'detail' => '',
            'out_trade_no' => $outTradeNo,
            'total_fee' => $total_fee, // 单位：分
            'notify_url' => config('app.url') . '/payment', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'openid' => Auth::guard('member')->user()->openid, // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
            'attach' => 'combo'
        ];
        ComboOrder::create(
            [
                'combo_id' => $combo_id,
                'activity_id' => $this->getActivityId($combo),
                'member_id' => Auth::guard('member')->user()->id,
                'price' => $total_num*$price,
                'outTradeNo' => $outTradeNo,
                'total_num'=>$total_num,
                'combo_price' => $combo->price,
                'times' => $total_num*$combo->times,
                'thumb' => $combo->thumb,
                'zhilv_price'=>$combo->zhilv_price,
                'rate'=>$combo->rate
            ]
        );
        return $arrtibutes;
    }

    public function getOrder()
    {
        return Cache::get('order' . Auth::guard('member')->id());
    }

    //生成订单id
    public function outTradeNo()
    {
        mt_srand((double)microtime() * 1000000);
        return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
    }

    protected function getActivityId($combo)
    {

        if ($activity = $this->checkActivity()) {
            $Activity = ComboActivityRelation::where('combo_id', $combo->id)->where('activity_id', $activity->id)->first();
            if ($Activity) {
                return $activity->id;
            }
        }
        return null;
    }

    public function getPrice($combo)
    {//计算价格

        if ($activity = $this->checkActivity()) {//当前是否存在活动
            $isActivity = ComboActivityRelation::where('combo_id', $combo->id)->where('activity_id', $activity->id)->first();
            if ($isActivity) {//查看活动打折方式
                $activityDetail = ComboActivities::findOrFail($isActivity->activity_id);
                if ($activityDetail->type == 1) {//折扣
                    return $activityDetail->rebate / 100 * $combo->price;
                } elseif ($isActivity->type == 2) {//减免活动

                }
            }
        }
        return $combo->price;
    }

    /**
     * @return mixed
     */
    public function checkActivity()
    {//检查当前是否有活动

        return $active = ComboActivities::where('start_time', '<', Carbon::now())
            ->where('end_time', '>', Carbon::now())
            ->where('status', '=', 1)
            ->first();
    }
    public function handle($notify){

        $payOrder = PayOrder::where('out_trade_no', $notify['out_trade_no'])->first();

        //  Log::info('notify',$notify);
        if ($payOrder) {
            if ($payOrder->is_pay == 1) {
                return true;
            }
            Log::info('支付3');
            $payOrder->is_pay = 1;
            $payOrder->save();
            if ($payOrder->attach == 'game') {
                Log::info('街道支付4');
              /*  $member = Member::where('openid', $notify['openid'])->firstOrfail();
                //增加一次
                $member->increment('game_num',1);*/
            } elseif ($payOrder->attach == 'combo') {
                Log::info('支付5');
                $distribute = new DistributeRepository();
                $order = ComboOrder::where('outTradeNo', $notify['out_trade_no'])->firstOrFail();
                //增加次数
                $member = Member::where('id', $order->member_id)->firstOrfail();
                $true = $member->increment('wallet_spots', $order->times);
                //抽奖
                $prize= new PrizeSetting();
                $prize->handlePrize($member->id,$payOrder);
                //分销
                $distribute->account($order->member_id, DistributeRepository::ACT_COMBO_BUY, ['order_id' => $order->id]);
                Log::info('支付6');

                event(new OrderShipped($order));
            }
            return '已处理';
        }
    }
    //退款 $is_refund 是否全退佣金
    public function refundOrder(ComboOrder $comboOrder,$is_refund=true){
        DB::transaction(function ()use ($comboOrder,$is_refund){

            if ($comboOrder->is_refund == 1) {

                throw new WechatException('此套餐已经退款');
            }

            //计算需要退款的余额
            $orderModel = new \App\Http\Controllers\Admin\Business\Service\ComboOrder();
            //查出订单
            $order = $orderModel->getComboOrder($comboOrder->id);
            $member=\App\Member::find($comboOrder->member_id);
            if ($is_refund&&$member->pid) {

                //计算分销价格
                $rateAry = get_real_rate($order);
                $parentMoney = $order->price * $rateAry['rate'] / 100;
                $topMoney = $order->price * $rateAry['top_rate'] / 100;
                //分享记录表
                $commission=new Commission();
                $commission->to_member=$member->pid;
                $commission->from_member=$member->id;
                $commission->price=$parentMoney;
                $commission->type=9;//退款
                $commission->desc='订单'.$comboOrder->outTradeNo.'退款';
                $commission->save();
                Member::where('id',$member->pid)->decrement('wallet_all_push_money',$parentMoney);
                Member::where('id',$member->pid)->decrement('wallet_push_money',$parentMoney);

            }
            //改变退款状态
            $comboOrder->is_refund = 1;
            $comboOrder->save();
            //减去用户表的使用次数
            Member::where('id',$comboOrder->member_id)->decrement('wallet_spots', $comboOrder->times);
            //写入退款记录表
            $combo = Combo::findOrFail($comboOrder->combo_id);
            $comboRefundLog = new ComboRefundLog();
            $comboRefundLog->member_id = $comboOrder->member_id;
            $comboRefundLog->refund_money = $comboOrder->price;
            $comboRefundLog->combo_name = $combo->title;
            $comboRefundLog->combo_id = $combo->id;
            $comboRefundLog->save();

            //微信退款api
         $wechat=app('wechat');
            $payment=$wechat->payment;

            $result = $payment->refund($comboOrder->outTradeNo, $comboOrder->outTradeNo, (int)round($comboOrder->price*100), (int)round($comboOrder->price*100));

            if ($result['return_code'] == 'FAIL') {
                throw  new WechatException($result['return_msg']);
            }
            if ($result['result_code'] == 'FAIL') {
                throw  new WechatException($result['err_code_des']);
            }
        });


    }
    protected  function refundleader(){

    }
    //查询支付状态
    public function searchWechatOrder($out_trade_no){
        $wechat=app('wechat');
        $payment=$wechat->payment;
        $pay= $payment->query($out_trade_no);
        if($pay->trade_state=="SUCCESS"){
            return 1;
        }else{
            return false;
        }
    }
}